package code20210917;

import java.util.LinkedList;
import java.util.List;

public class C54 {

	public static void main(String[] args) {
		int[][] matrix = {
				{1,2},{3,4},
		};
		for(int n:spiralOrder(matrix)) {
			System.out.println(n);
		}
	}
	public static List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> result = new LinkedList<>();
		int top = 0;
		int bottom = matrix.length-1;
		int left = 0;
		int right = matrix[0].length-1;
		while(top<=bottom&&left<=right) {
			for(int i=left;i<=right;i++) {
				if(top<=bottom) result.add(matrix[top][i]);
			}
			top++;
			for(int i=top;i<=bottom;i++) {
				if(left<=right) result.add(matrix[i][right]);
			}
			right--;
			for(int i=right;i>=left;i--) {
				if(bottom>=top) result.add(matrix[bottom][i]);
			}
			bottom--;
			for(int i=bottom;i>=top;i--) {
				if(left<=right) result.add(matrix[i][left]);
			}
			left++;
		}
		return result;
    }
}
